﻿
var map = null;
var M_STATUS;
var geometryService;
var findParams;
var findTask;
var infoTemplate;
var tabResult = null;
var symbolPolygon = null;// new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SHORTDASH, new dojo.Color([0, 0, 255]), 2), new dojo.Color([0, 0, 255, 0.15]));
dojo.addOnLoad(init);

//设置搜索框获取焦点事件和下拉菜单的显示和隐藏
function resizePage() {
    $("#searchbox").focus(function () {
        if ($("#div_setting").css("display") == "block") {
            $("#div_setting").css("display", "none");
        }
    });
    $("#div_setting").click(function (e, e3) {
        e.stopPropagation();
    });
    $("body").click(function (e) {
        if ($("#div_setting").css("display") == "block") {
            $("#div_setting").css("display", "none");
        }
    });
    var height = $(".clssetting").height();
    $(".clssetting .innercenter").css("height", height - 40);
}

//body的onload事件
function funload() {

    resizePage();
    //初始化结果列表tab
    tabResult = new tabControl("id_div_queryresult");
    $("#searchbox").keydown(inputkeydown);
    $("input[type='checkbox']").each(function (index, ele) {
        var id = $(ele).next("a").attr("id");
        var html = "<div style='margin-left:10px;width:100px;' id='" + id + "_slider'></div>";
        $(ele).parent().append(html);
        $("#" + id + "_slider").slider({
            value: 100,
            orientation: "horizontal",
            range: "min",
            animate: true,
            slide: function (event, ui) {
                var title = $(ele).next("a")[0].innerHTML;
                var layer = GetLayerByKeyValue("className", title);
                if (layer != null) {
                    layer.setOpacity(ui.value / 100);
                }
            }
        });
    });
}
var mapConfig = null;
function getMapConfig() {
    GetSmJSON(DBCenterServiceUrl + "/Map.asmx/GetMapConfig", "", successFun)
    function successFun(json) {
        mapConfig = JSON.parse(json);
    }
}
function getInnerLayerFromConfig(layername, innerlayername) {
    var layer = getLayerFromConfig(layername);
    if (layer != null) {
        for (var i = 0; i < layer.InnerLayers.length; i++) {
            if (layer.InnerLayers[i].Name == innerlayername) {
                return layer.InnerLayers[i]
            }
        }
    }
    return null;
}
function getLayerFromConfig(layername) {
    if (mapConfig != null) {
        for (var i = 0; i < mapConfig.Layers.length; i++) {
            if (mapConfig.Layers[i].Name == layername) {
                return mapConfig.Layers[i];
            }
        }
    }
    return null;
}
function getQueryAbleInnerLayerIDs(layername) {
    var queryAbleInnerLayerIDs = [];
    var lay = GetLayerByKeyValue("className", layername);
    if (lay != null) {
        for (var i = 0; i < lay.layerInfos.length; i++) {
            var innerlayername = lay.layerInfos[i].name;
            var innerlayerconfig = getInnerLayerFromConfig(layername, innerlayername);
            if (innerlayerconfig == null || innerlayerconfig.QueryAble) {
                queryAbleInnerLayerIDs[queryAbleInnerLayerIDs.length] = i;
            }
        }
    }
    return queryAbleInnerLayerIDs;
}
function getInnerLayerIdByName(layerName, innerLayerName) {
    var innerLayerId = -1;
    var lay = GetLayerByKeyValue("className", layerName);
    if (lay != null) {
        for (var i = 0; i < lay.layerInfos.length; i++) {
            if (lay.layerInfos[i].name == innerLayerName) {
                innerLayerId = i; break;
            }
        }
    }
    return innerLayerId;
}


function getBaseLayerFromConfig() {
    var blayer = null;
    for (var i = 0; i < mapConfig.Layers.Length; i++) {
        if (mapconfig.Layers[i].BaseLayer) {
            blayer = mapConfig.Layers[i];
            break;
        }
    }
    return blayer;
}

function addLayer(layer, map) {
    switch (layer.LayerType) {
        case "ArcGISDynamicMapServiceLayer":
            addArcGISDynamicMapServiceLayer(layer, map);
            break;
        case "ArcGISImageServiceLayer":
            addArcGISImageServiceLayer(layer, map); break;
    }
    if (layer.QueryAble == null || layer.QueryAble) {
        var html = '<dt onclick="spanclick(this)" layername="' + layer.Name + '"><span class="checkbox" ischecked="true" checked="checked"></span>' + layer.Name + ' </dt>';
        $("#div_setting .innercenter dl").append(html);
    }
}
var loadedLayerCount = 0;
function addArcGISDynamicMapServiceLayer(layer, map) {
    var lay = new esri.layers.ArcGISDynamicMapServiceLayer(layer.Url, { className: layer.Name });
    lay.visible = layer.Visible;
    lay.opacity = layer.Opacity / 100;
    lay.onLoad = function () {
        var innerlayerlength = lay.layerInfos.length;
        var visibleInnerlayerIds = [];
        for (var i = 0; i < innerlayerlength; i++) {
            var innerlayer = getInnerLayerFromConfig(layer.Name, lay.layerInfos[i].name);
            if (innerlayer == null || innerlayer.Visible == null || innerlayer.Visible) {
                visibleInnerlayerIds[visibleInnerlayerIds.length] = i;
            }
        }
        lay.setVisibleLayers(visibleInnerlayerIds);
        addLayerToLayerControl(lay);
        loadedLayerCount++;
        if (loadedLayerCount == mapConfig.Layers.length) {
            //            if (parent.afterYztLoaded != null) {
            //                parent.afterYztLoaded();
            //            }
            if (pp != null) {
                locateByPoints(pp);
            }
        }
    };
    map.addLayer(lay);
}
function addLayerToLayerControl(lay) {
    var newNode = { name: lay.className, open: true };
    newNode.children = [];
    var layer = getLayerFromConfig(lay.className);
    newNode.checked = layer.Visible;
    if (mapConfig.ShowInnerLayersInLayersControl && layer.ShowInnerLayersInLayersControl) {
        for (var i = 0; i < lay.layerInfos.length; i++) {
            var innerLayerConfig = getInnerLayerFromConfig(lay.className, lay.layerInfos[i].name);
            if (innerLayerConfig != null && innerLayerConfig.ShowInLayersControl == true) {
                newNode.children[newNode.children.length] = { name: innerLayerConfig.Name, checked: innerLayerConfig.Visible };
            }
        }
    }
    zTreeObj.addNodes(null, newNode);
}

function addArcGISImageServiceLayer(layer, map) {
}
var zTreeObj = null;
function initZtree() {
    setting = { view: { selectedMulti: false },
        check: { enable: true, chkboxType: { "Y": "", "N": ""} },
        callback: { onCheck: zTreeOnCheck }
    }
    zTreeObj = $.fn.zTree.init($("#id_div_layerscontrol"), setting);
}

function zTreeOnCheck(event, treeId, treeNode) {
    if (treeNode.level == 0) {
        var llayer = GetLayerByKeyValue("className", treeNode.name);
        if (llayer != null) {
            llayer.setVisibility(treeNode.checked);
        }
    }
    else if (treeNode.level == 1) {
        var name = treeNode.name;
        var pnode = treeNode.getParentNode();
        var l = GetLayerByKeyValue("className", pnode.name);
        var innerlayerid = 0;
        for (var j = 0; j < l.layerInfos.length; j++) {
            if (l.layerInfos[j].name == name) {
                innerlayerid = j; break;
            }
        }
        var ids = l.visibleLayers;
        if (treeNode.checked) {
            ids[ids.length] = innerlayerid;
            l.setVisibleLayers(ids);
        }
        else {
            var idsNew = [];
            for (var m = 0; m < ids.length; m++) {
                if (ids[m] != innerlayerid) {
                    idsNew[idsNew.length] = ids[m];
                }
                if (idsNew.length == 0) {
                    idsNew[0] = -1;
                }
            }
            l.setVisibleLayers(idsNew);
        }

    }
}

//初始化地图，包括加载图层等
function init() {
    initZtree();
    getMapConfig();
    esri.config.defaults.io.proxyUrl = "../proxy.ashx";
    symbolPolygon = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SHORTDASH, new dojo.Color([0, 0, 255]), 2), new dojo.Color([0, 0, 255, 0.15]));
    if (mapConfig != null) {
        geometryService = new esri.tasks.GeometryService(mapConfig.GeometryServiceUrl);
        var mapoption = {};
        var sr = null;
        //设置坐标系
        if (mapConfig.SpatialReferenceType != null) {
            sr = new esri.SpatialReference(mapConfig.SpatialReferenceValue);
        }
        else {
            sr = new esri.SpatialReference({ 'wkid': '4326' });
        }
        //设置地图初始范围
        var startExtent=null;
        if (mapConfig.Extent != null) {
             startExtent= new esri.geometry.Extent(mapConfig.Extent.Left, mapConfig.Extent.Bottom, mapConfig.Extent.Right, mapConfig.Extent.Top, sr);
            mapoption.extent = startExtent;
        }
        //设置地图中心点
        if (mapConfig.Center != null) {
            point = esri.geometry.Point(mapConfig.Center.X, mapConfig.Center.Y, sr);
            mapoption.center = point;
        }
        mapoption.spatialReference = sr;
        map = new esri.Map("div_map", mapoption);
        //要先加载基础图层（BaseLayer）
        //        var baseLayer = getBaseLayerFromConfig();
        //        if (baseLayer != null) {
        //            addLayer(baseLayer);
        //        }

        for (var i = 0; i < mapConfig.Layers.length; i++) {
            if (mapConfig.Layers[i].Load) {
                addLayer(mapConfig.Layers[i], map);
            }
        }
        map.setMapCursor("move");
        map.centerAndZoom(point, mapConfig.StartZoomLevel);
        toolbar = new esri.toolbars.Draw(map, { showToolTip: false });
        navToolbar = new esri.toolbars.Navigation(map);
        dojo.connect(navToolbar, "onExtentHistoryChange", extentHistoryChangeHandler);
        dojo.connect(toolbar, "onDrawEnd", afterMeasureDraw);
        dojo.connect(map, "onMouseMove", showCoordinates);
        dojo.connect(map, "onMouseDrag", showCoordinates);

        initQueryParams();
        map.setExtent(startExtent);
        var p = $.query.get("p");
        if(p!=null &&p!="" && p!="undefined")
        {
         pp= JSON.parse(p);
       }
    }
}
var pp=null;
var afterLoaded=null;
function initQueryParams() {

    findParams = new esri.tasks.FindParameters();
    findParams.returnGeometry = true;
    infoTemplate = new esri.InfoTemplate("${XZQMC}", "名称：${XZQMC}");
}
function pan() {

    toolbar.deactivate();
    map.showZoomSlider();
    M_STATUS = STATUS.PAN;
    map.setMapCursor("move");
    map.enablePan();
    var html = '<li><a href="#accordion3">Title3</a></li>';
    $("#make-accordion ul").append(html);
}
function zoomin() {

    navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
}
function zoomout() {
    navToolbar.activate(esri.toolbars.Navigation.ZOOM_OUT);
}
function fullextend() {
    navToolbar.zoomToFullExtent();
}
function preview() {
    navToolbar.zoomToPrevExtent();
}
function nextview() {
    navToolbar.zoomToNextExtent();
}
function clearscreen() {
    map.graphics.clear();
    pan();
}
//当地图视图发生变化时后判定前一视图和后一视图的状态
function extentHistoryChangeHandler() {
    //    if (!navToolbar.isFirstExtent()) {
    //        dojo.byId("zoomprev").disabled = false;
    //        dojo.byId("zoomprev").src = "images/nav_previous.png";
    //    }
    //    else {
    //        dojo.byId("zoomprev").disabled = true;
    //        dojo.byId("zoomprev").src = "images/d-nav_previous.png";
    //    }

    //    if (!navToolbar.isLastExtent()) {
    //        dojo.byId("zoomnext").disabled = false;
    //        dojo.byId("zoomnext").src = "images/nav_next.png";
    //    }
    //    else {
    //        dojo.byId("zoomnext").disabled = true;
    //        dojo.byId("zoomnext").src = "images/d-nav_next.png";
    //    }
}




/*****************************地图查询Start***********************************************/

function selLayerOK() {
    $("#div_setting").css("display", "none");
}
function settingClick(ele, e) {

    if ($("#div_setting").css("display") == "block") {
        $("#div_setting").css("display", "none");
    }
    else {
        var ipt = $(ele).prev("input:first");
        var left = $(ipt).offset().left;
        var width = $(ipt).width() + $(ele).width();
        var top = $(ipt).offset().top + $(ipt).height() + 3;
        $("#div_setting").css("left", left + 1);
        $("#div_setting").css("width", width);
        $("#div_setting").css("top", top + 1);
        $("#div_setting").css("display", "block");
    }
    event.cancelBubble = true;
}
function spanclick(ele2) {
    var ele = $(ele2).find("span");
    if ($(ele).attr("ischecked") == "true" || $(ele).attr("checked") == true) {
        $(ele).css("background", "url(../mapimages/checkbox2.png)");
        $(ele).css("background-position", "0 2px");
        $(ele).attr("ischecked", "false");
        $(ele2).css("background-color", "#EFF2F7");
    }
    else {
        $(ele).css("background", "url(../mapimages/checkbox1.png)");
        $(ele).css("background-position", "0 2px");
        $(ele).attr("ischecked", "true");
        $(ele2).css("background-color", "rgb(217, 230, 248)");
    }
}

function inputkeydown() {
    var theEvent = window.event || e;
    var code = theEvent.keyCode || theEvent.which;
    if (code == "13") {
        queryByAttribute();
    }
}
function queryByAttribute() {
    tabResult.removeAllPages();
    var value = $("#searchbox").val();
    if (value != null && value != "") {
        map.graphics.clear();
        findParams.searchText = value;
        var layerids = map.layerIds;
        var eles = $("#div_setting dt");
        for (var i = 0; i < eles.length; i++) {
            var dt = eles[i];
            if ($(dt).find("span").attr("ischecked") == "true" || $(dt).find("span").attr("ischecked") == true) {
                var layername = $(dt).attr("layername");
                var layer = GetLayerByKeyValue("className", layername);
                var url = layer.url;
                findParams.layerIds = getQueryAbleInnerLayerIDs(layername);
                findTask = new esri.tasks.FindTask(url);
                findTask.layername = "sdfas";
                var showqueryresult = new showQueryResultsEX();
                showqueryresult.layerName = layername;
                findTask.execute(findParams, showqueryresult.showResult);
            }
        }
    }
}

function showQueryResultsEX() {
    this.layerName = "";
    var _self = this;
    this.showResult = function (result) {
        var index = 0;
        if ($("#id_div_queryresult").css("display") != "block") {
            var wid = $("#div_map").width();
            var hei = $("#div_map").height();
            var top = hei - 100;
            $("#id_div_queryresult").css("bottom", 20).css("right", "4px").css("width", wid - 8).css("margin-left", 2).css("display", "block");
        }
        if (result != null && result.length > 0) {
            var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SHORTDASH, new dojo.Color([0, 0, 255]), 2), new dojo.Color([0, 0, 255, 0.15]));
            for (var i = 0; i < result.length; i++) {
                var re = result[i];
                if (re != null) {
                    re.feature.symbol = symbol;

                    var str = "<table border=1 style='margin:0;padding:0;border-color:gray;border-collapse: collapse;width:100%'><tbody><tr style='background-color:rgb(205, 221, 229);height:20px;font-weight:bolder'><td>属性名</td><td>属性值</td></tr>";

                    var tag = "graphics_" + _self.layerName + "_" + re.layerName + "_" + index;
                    index++;
                    /*****************插入列表*******************/
                    var resulthtml = "";
                    var exists = true;
                    if (tabResult.getTabPage(re.layerName) == null || tabResult.getTabPage(re.layerName).length <= 0) {
                        exists = false;
                        tabResult.addTabPage(re.layerName, re.layerName + "层查询结果");
                        resulthtml = '<table border=true><tr class="rowtitle">';

                        var innerlayer = getInnerLayerFromConfig(_self.layerName, re.layerName);
                        if (innerlayer != null && innerlayer.FieldNames != null && innerlayer.FieldNames.length > 0) {
                            for (var p in innerlayer.FieldCaptions) {
                                resulthtml += '<td>' + innerlayer.FieldCaptions[p] + '</td>';
                            }
                        }
                        else {
                            for (var p in re.feature.attributes) {
                                if (typeof (re.feature.attributes[p]) == "string") {
                                    resulthtml += '<td>' + p + '</td>';
                                }
                            }
                        }
                        resulthtml += '</tr></table>';
                        var page = tabResult.getTabPage(re.layerName);
                        page.append(resulthtml);
                    }

                    resulthtml = "<tr tag=" + tag + " ondblclick='fundbclick(this)' class='rowcontent'>";
                    if (innerlayer != null && innerlayer.FieldNames != null && innerlayer.FieldNames.length > 0) {
                        for (var p in innerlayer.FieldNames) {
                            var fieldname = innerlayer.FieldNames[p];
                            if (fieldname == re.foundFieldName) {
                                str += "<tr><td style='line-height: 13px;color:red'>" + innerlayer.FieldCaptions[p] + "</td><td style='line-height: 13px;color:red'>" + re.feature.attributes[fieldname] + "</td></tr>";
                                resulthtml += "<td  style='color:red'>" + re.feature.attributes[fieldname] + "</td>";
                            }
                            else {
                                str += "<tr><td  style='line-height: 13px;'>" + innerlayer.FieldCaptions[p] + "</td><td  style='line-height: 13px;'>" + re.feature.attributes[fieldname] + "</td></tr>";
                                resulthtml += "<td>" + re.feature.attributes[fieldname] + "</td>";
                            }
                        }
                    }
                    else {
                        for (var p in re.feature.attributes) {
                            if (typeof (re.feature.attributes[p]) == "string") {

                                if (p == re.foundFieldName) {
                                    str += "<tr><td style='line-height: 13px;color:red'>" + p + "</td><td style='line-height: 13px;color:red'>" + re.feature.attributes[p] + "</td></tr>";
                                    resulthtml += "<td  style='color:red'>" + re.feature.attributes[p] + "</td>";
                                }
                                else {
                                    str += "<tr><td  style='line-height: 13px;'>" + p + "</td><td  style='line-height: 13px;'>" + re.feature.attributes[p] + "</td></tr>";
                                    resulthtml += "<td>" + re.feature.attributes[p] + "</td>";
                                }
                            }
                        }
                    }
                    resulthtml += "</tr>";
                    tabResult.getTabPage(re.layerName).find("table").append(resulthtml);
                    str += "</tbody></table>";
                    infoTemplate = new esri.InfoTemplate("图层:" + re.layerName + "-" + re.foundFieldName + ":${XZQMC}", str);
                    re.feature.infoTemplate = infoTemplate;
                    re.feature.tag = tag;
                    map.graphics.add(re.feature);
                    re.feature.hide();
                }
            }
        }
    }
}



//查询结果tr双击事件
function fundbclick(ele) {
    var tag = $(ele).attr("tag");
    locateGraphicByTag(tag);
}
//根据Tag获取Graphic
function getGraphicByTag(tag) {
    for (var i = 0; i < map.graphics.graphics.length; i++) {
        if (map.graphics.graphics[i].tag == tag) {
            return map.graphics.graphics[i];
        }
    }
    return null;
}
//定位某个Graphic
var m_locateGraphic = null;
function locateGraphicByTag(ele) {
    var tag = ele;
    if (m_locateGraphic != null) {
        m_locateGraphic.hide();
    }
    map.infoWindow.hide();
    var grap = getGraphicByTag(tag);
    if (grap != null) {
        map.infoWindow.setFeatures([grap]);
        map.infoWindow.show(grap.geometry.getCentroid());
        m_locateGraphic = grap;
        grap.show();
        map.setExtent(grap._extent);
    }
}
/*****************************地图查询End***********************************************/
function testLocate() {
    // locateGraphicByModelAndSql("XZQDW", "XZQMC LIKE '%县食品公司%'");
    //locateGraphicByModelAndSql("ZDDW", "DJH LIKE '%6542260020080256000%'");
    var parts = new Array();
    for (var i = 1; i < 3; i++) {
        var part = new Array();
        for (var j = 0; j < 5; j++) {
            var pt = new Toint(j + 2, j + 4);
            part[part.length] = pt;
        }
        parts[parts.length] = part;
    }
    //locateByPoints(parts, null, null);
    locateByPoints([[[29463426.457919367, 5095055.50776774], [29511606.10632875, 5091077.371660544], [29505417.89460644, 5034057.420790725], [29431601.369061794, 5041571.677882097]]], ["FID","FFF","FDF"],["ASDF","ASDF","ASDF"]);
}
function Toint(xx, yy) {
    this.x = xx;
    this.y = yy;
}

function locateByPoints(parts, fields, fieldValues) {

    var polygon = new esri.geometry.Polygon(map.spatialReference);
    for (var i = 0; i < parts.length; i++) {
        var part = parts[i];
        var ring = [];
        for (var j = 0; j < part.length; j++) {
            ring[ring.length] = [part[j][0] || part[j].x, part[j][1] || part[j].y];
        }
        var xstart = part[0][0] || part[0].x;
        var ystart = part[0][1] || part[0].y;
        var xend = part[part.length - 1][0] || part[part.length - 1].x;
        var yend = part[part.length - 1][1] || part[part.length - 1].y;
        if (!(xstart == xend && ystart == yend)) {
            ring[ring.length] = [xstart, ystart];
        }
        polygon.addRing(ring);
    }
    var str = getInfoTemplateString();
    for (var p in fields) {
        str += "<tr><td  style='line-height: 13px;'>" + fields[p] + "</td><td  style='line-height: 13px;'>" + fieldValues[p] + "</td></tr>";
    }
    var infoTemplate = new esri.InfoTemplate("定位地块", str);
    var graphic = new esri.Graphic(polygon, symbolPolygon, null, infoTemplate);
    map.graphics.clear();
    map.graphics.add(graphic);
    map.setExtent(graphic.geometry.getExtent().expand(3));
}

function getInfoTemplateString() {
    var str = "<table border=1 style='margin:0;padding:0;border-color:gray;border-collapse: collapse;width:100%'><tbody><tr style='background-color:rgb(205, 221, 229);height:20px;font-weight:bolder'><td>属性名</td><td>属性值</td></tr>";
    return str;
}

function locateGraphicByModelAndSql(modelName, sqlFilter) {
    var model = getLocateModelFromConfig(modelName);
    if (model != null) {
        var layername = model.LayerName;
        var innerLayerName = model.InnerLayerName;
        var layer = getLayerFromConfig(layername);
        if (layer != null) {
            var layerUrl = layer.Url;
            var innerLayerID = getInnerLayerIdByName(layername, innerLayerName);
            if (innerLayerID >= 0) {
                var QueryTask = new esri.tasks.QueryTask(layerUrl + "/" + innerLayerID);
                var query = new esri.tasks.Query();
                query.where = sqlFilter;
                query.outFields = ["*"];
                query.returnGeometry = true;
                QueryTask.execute(query, locateSuccess);
            }
        }
        function locateSuccess(result) {
            map.graphics.clear();
            var extend = null;
            var innerlayer = getInnerLayerFromConfig(layername, innerLayerName);
            for (var i = 0; i < result.features.length; i++) {
                var feature = result.features[i];
                if (result.geometryType == "esriGeometryPolygon") {
                    feature.symbol = symbolPolygon;
                }
                var str = getInfoTemplateString();
                if (innerlayer != null && innerlayer.FieldNames != null && innerlayer.FieldNames.length > 0) {
                    for (var p in innerlayer.FieldNames) {
                        var fieldname = innerlayer.FieldNames[p];
                        str += "<tr><td  style='line-height: 13px;'>" + innerlayer.FieldCaptions[p] + "</td><td  style='line-height: 13px;'>" + feature.attributes[fieldname] + "</td></tr>";
                    }
                }
                else {
                    for (var p in feature.attributes) {
                        str += "<tr><td  style='line-height: 13px;'>" + p + "</td><td  style='line-height: 13px;'>" + feature.attributes[p] + "</td></tr>";
                    }
                }
                var infoTemplate = new esri.InfoTemplate("图层:" + layername + "-" + innerLayerName, str);
                feature.infoTemplate = infoTemplate;
                map.graphics.add(feature);
                if (extend == null)
                    extend = feature.geometry.getExtent();
                else
                    extend = extend.union(feature.geometry.getExtent());
            }
            if (extend != null) {
                map.setExtent(extend);
            }
        }
    }
}
function getLocateModelFromConfig(modelName) {
    var model = null;
    if (mapConfig != null) {
        for (var i = 0; i < mapConfig.LocateConfig.Models.length; i++) {
            if (mapConfig.LocateConfig.Models[i].Name == modelName) {
                model = mapConfig.LocateConfig.Models[i]; break;
            }
        }
    }
    return model;
}


/****************************添加图层、图层控制等Start*********************************/

//显示XY坐标
function showCoordinates(event) {
    var mp = event.mapPoint;
    dojo.byId("info").innerHTML = mp.x + ", " + mp.y;
}

//根据图层名获取图层
function GetLayerByKeyValue(key, value) {
    var result = null;
    for (var i = 0; i < map.layerIds.length; i++) {
        var id = map.layerIds[i];
        if (map.getLayer(id)[key] == value) {
            result = map.getLayer(id); break;
        }
    }
    return result;
}
/****************************添加图层、图层控制等End*********************************/



/******************************距离量算部分Start******************************************/
//切换到平移状态，启用平移，设置光标

//关闭量算结果div
function closeresult() {
    $("#div_measureresult").css("display", "none");

    map.graphics.clear();
    toolbar.deactivate();
    map.showZoomSlider();
    M_STATUS = STATUS.PAN;
    map.setMapCursor("move");
    map.enablePan();

}
//开始距离量算
function startMeasureDistance() {
    M_STATUS = STATUS.MEASUREDISTANCE;
    toolbar.activate(esri.toolbars.Draw.POLYLINE);
    toDraw();
}
//开始距离面积
function startMeasureArea() {
    M_STATUS = STATUS.MEASUREAREA;
    toolbar.activate(esri.toolbars.Draw.POLYGON);
    toDraw();
}
//设置地图光标，禁用平移
function toDraw() {
    map.hideZoomSlider();
    map.setMapCursor("crosshair");
    map.disablePan();
}
//绘制结束
function afterMeasureDraw(geometry) {
    switch (geometry.type) {
        case "polyline":
            var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 255]), 2);
            break;
        case "polygon":
            var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]));
            break;
    }
    var graphic = new esri.Graphic(geometry, symbol);
    map.graphics.clear();
    map.graphics.add(graphic);
    callLength(graphic);
}
//调用计算长度、面积方法
function callLength(graphic) {
    if (M_STATUS == STATUS.MEASUREDISTANCE) {
        var lengthParams = new esri.tasks.LengthsParameters();
        lengthParams.polylines = [graphic.geometry];
        lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
        lengthParams.geodesic = true;
        geometryService.lengths(lengthParams, showMeasureResult);
    }
    else if (M_STATUS == STATUS.MEASUREAREA) {
        var areaAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
        areaAndLengthParams.polygons = [graphic.geometry];
        areaAndLengthParams.lengthUnit = areaAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_METER;
        geometryService.areasAndLengths(areaAndLengthParams, showMeasureResult);
    }
}
//显示计算结果
function showMeasureResult(result) {
    if (M_STATUS == STATUS.MEASUREDISTANCE) {
        var unit = "米";
        var length = result.lengths[0];
        if (length > 1000) {
            length = length / 1000; unit = "公里";
        }
        length = BetMathRound(length, 4);
        var resultstr = "总长度:" + length + unit + '<p class="close" onclick="closeresult()" >x</p>';
    }
    else if (M_STATUS == STATUS.MEASUREAREA) {
        var unit = "平方米";
        var area = result.areas[0];
        if (area > 10000) {
            area = area / 1000; unit = "公顷";
        }
        area = BetMathRound(area, 4);
        var resultstr = "总面积:" + area + unit + '<p class="close" onclick="closeresult()" >x</p>';
    }
    $("#div_measureresult").html(resultstr);
    var width = $("#div_map").width();
    var innerwidth = $("#div_measureresult").width();
    var left = (width - innerwidth) / 2;
    $("#div_measureresult").css("left", left);
    $("#div_measureresult").css("display", "block");
}
/******************************距离量算部分End******************************************/


var STATUS = {
    MEASUREDISTANCE: "1",
    MEASUREAREA: "2",
    PAN: "3"
}
